import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:shared_preferences/shared_preferences.dart';

class UserInfo {
  String? babyName;
  String? userIcon;
  String? userId;
  String? token;
  bool? isVip;

  UserInfo({this.babyName, this.userIcon, this.userId, this.token, this.isVip});

  UserInfo.fromJson(Map<String, dynamic> json) {
    babyName = json['babyName'];
    userIcon = json['userIcon'];
    userId = json['userId'];
    token = json['token'];
    isVip = json['isVip'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['babyName'] = babyName;
    data['userIcon'] = userIcon;
    data['userId'] = userId;
    data['token'] = token;
    data['isVip'] = isVip;
    return data;
  }
}

class UserManager extends ChangeNotifier {
  static final UserManager _instance = UserManager._internal();
  final String _userInfoKey = "accountInfo";
  UserInfo? _userInfo;

  bool _isVip = false;

  UserManager._internal() {
    _initUserInfo();
  }

  static UserManager get instance => _instance;

  void _initUserInfo() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? userInfoText = prefs.getString(_userInfoKey);
    if (userInfoText != null) {
      _userInfo = UserInfo.fromJson(json.decode(userInfoText));
      notifyListeners();
    }
  }

  UserInfo? get userInfo => _userInfo;

  bool isLogin() => userInfo != null;

  // bool isVip() => userInfo?.isVip == true;
  bool isVip() => _isVip;

  void updateUserInfo(String jsonInfo) {
    _userInfo = UserInfo.fromJson(json.decode(jsonInfo));
    _updateCacheAndNotify();
  }

  // void updateVipState(bool isVip) {
  //   if (_userInfo != null) {
  //     _userInfo!.isVip = isVip;
  //     _updateCacheAndNotify();
  //   }
  // }

  void updateVipState(bool isVip) {
    _isVip = isVip;
    notifyListeners();
  }

  String? get token => _userInfo?.token;

  void loginOut() {
    _userInfo = null;
    _updateCacheAndNotify();
  }

  void _updateCacheAndNotify() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if (_userInfo != null) {
      prefs.setString(_userInfoKey, json.encode(_userInfo));
    } else {
      prefs.remove(_userInfoKey);
    }
    notifyListeners();
  }
}





